package servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		System.out.println(isMultipart);
		if(isMultipart) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(5*1024);
			File repository = new File("e:/temp");
			factory.setRepository(repository);
			
			//DiskFileItemFactory factory1 = new DiskFileItemFactory(5*102, repository);
			
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			upload.setSizeMax(12*1024);
			upload.setFileSizeMax(10*1024);
			try {
				List<FileItem> items = upload.parseRequest(request);
				
				for(FileItem item:items) {
					System.out.println(item);
					if(item.isFormField()) {
						String fname = item.getFieldName();
						String fval = item.getString();
						System.out.println(fname + ":" + fval);
					}else {
						String fieldName = item.getFieldName();
					    String fileName = item.getName();
					    System.out.println("isInMemory:"+item.isInMemory());
					    File uploadedFile = new File("e:/upload/"+fileName);
					    try {
							item.write(uploadedFile);
							InputStream uploadedStream = item.getInputStream();
							//byte[] b =  item.get();
							//MyExcelUtils.parse(b);
//							OutputStream os = new FileOutputStream(uploadedFile);
//							byte[] buffer = new byte[1024];
//							int len = 0;
//							while((len = uploadedStream.read(buffer))>0) {
//								os.write(buffer, 0, len);
//							}
//							os.close();
						    uploadedStream.close();
						    
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					    finally {
							item.delete();
						}
					}
				}
				
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		
		
	}

}
